package com.xiayuanxing.arithmetic.DataStructures.SparseArray;

/**
 * @program: arithmetic
 * @description: 稀疏数组(二维数组与稀疏数组的转化)
 * @author: xia yuan xing
 * @create: 2021-08-28 14:54
 */
public class sparseArray1 {


//   原始二维数组
//    1.创建一个原始的二维数组
//    2.0代表没有棋子   1.代表黑子   2.代表蓝子

    public static void main(String[] args) {
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;

//        输出原始的二维数组
        System.out.println("输出原始的二维数组:");
        for (int[] ints : chessArr1) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
        System.out.println();


        //将二维数组转换成稀疏数组
//    1.获取原始二维数组中的有效数据个数
        int sum =0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0){
                    sum++;
                }
            }
        }

//        2.创建稀疏数组
        int sparseArr1[][] = new int[sum+1][3];
        sparseArr1[0][0] = 11;
        sparseArr1[0][1] = 11;
        sparseArr1[0][2] = sum;

//      用于记录是第几个非0数据
        int count = 0;
//        3.遍历二维数组，将数据存放到稀疏数组中
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0){
                    count++;
                   sparseArr1[count][0] = i;
                   sparseArr1[count][1] = j;
                   sparseArr1[count][2] = chessArr1[i][j];
                }
            }
        }

//        输出稀疏数组
        System.out.println("输出稀疏数组:");
        for (int i = 0; i < sparseArr1.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n",sparseArr1[i][0],sparseArr1[i][1],sparseArr1[i][2]);
        }
        System.out.println();


        //将稀疏数组转换成二维数组

//        1.创建原始二维数组
        int chessArr2[][] = new  int[sparseArr1[0][0]][sparseArr1[0][1]];
//        2.将稀疏数组循环，将有效值写进原始二维数组
        for (int i = 1; i < sparseArr1.length; i++) {
            chessArr2[sparseArr1[i][0]][sparseArr1[i][1]] = sparseArr1[i][2];
            chessArr2[sparseArr1[i][0]][sparseArr1[i][1]] = sparseArr1[i][2];
        }

        System.out.println("稀疏数组转化为原始数组:");
        for (int[] ints : chessArr2) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }



    }
}